﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;

public partial class MaterialPlan : System.Web.UI.Page
{
    uMESZZBusiness bll = new uMESZZBusiness();

    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：进料计划";
        master.strTitle = "进料计划";
        master.ChangeFrame(true);

        if (!IsPostBack)
        {
            BindFactory();
            BindFamily();
            BindTeam();
            BindStation();
            BindType();
            SetTempColumn();
        }
    }



    #region 设置模板列值
    protected void SetTempColumn()
    {
        DataTable dtFactory = (DataTable)Session["DT_Factory"];
        DataTable dtTeam = (DataTable)Session["DT_Team"];
        DataTable dtStation = (DataTable)Session["DT_WorkStation"];

        var ddlF = ItemGrid.Columns.FromKey("FactoryID");
        foreach (DataRow row in dtFactory.Rows)
        {
            ddlF.ValueList.ValueListItems.Add(row["FactoryID"].ToString(), row["FactoryName"].ToString());
        }

        var ddlT = ItemGrid.Columns.FromKey("TeamID");
        foreach (DataRow row in dtTeam.Rows)
        {
            ddlT.ValueList.ValueListItems.Add(row["TeamID"].ToString(), row["TeamName"].ToString());
        }

        var ddlWS = ItemGrid.Columns.FromKey("WorkStationID");
        foreach (DataRow row in dtStation.Rows)
        {
            ddlWS.ValueList.ValueListItems.Add(row["WorkStationID"].ToString(), row["WorkStationName"].ToString());
        }
    }
    #endregion

    #region 绑定车间数据
    private void BindFactory()
    {
        DataTable dt = bll.GetFactory();
        ddlFactory.DataSource = dt;
        ddlFactory.DataTextField = "FactoryName";
        ddlFactory.DataValueField = "FactoryID";
        ddlFactory.DataBind();
        ddlFactory.Items.Insert(0, new ListItem("", ""));

        Session["DT_Factory"] = dt.Copy();
    }
    #endregion

    #region 绑定车型数据
    private void BindFamily()
    {
        DataTable dt = bll.GetFamily();
        ddlFamily.DataSource = dt;
        ddlFamily.DataTextField = "ProductFamilyName";
        ddlFamily.DataValueField = "FamilyID";
        ddlFamily.DataBind();
        ddlFamily.Items.Insert(0, new ListItem("", ""));
    }
    #endregion

    #region 绑定班组数据
    private void BindTeam()
    {
        DataTable dt = bll.GetTeam();
        ddlTeam.DataSource = dt;
        ddlTeam.DataTextField = "TeamName";
        ddlTeam.DataValueField = "TeamID";
        ddlTeam.DataBind();
        ddlTeam.Items.Insert(0, new ListItem("", ""));

        Session["DT_Team"] = dt.Copy();
    }
    #endregion

    #region 绑定配送地点数据
    private void BindStation()
    {
        DataTable dt = bll.GetStation();
        ddlStation.DataSource = dt;
        ddlStation.DataTextField = "WorkStationName";
        ddlStation.DataValueField = "WorkStationID";
        ddlStation.DataBind();
        ddlStation.Items.Insert(0, new ListItem("", ""));

        Session["DT_WorkStation"] = dt.Copy();
    }
    #endregion

    #region 绑定类型数据
    private void BindType()
    {
        ddlType.Items.Insert(0, new ListItem("BOM", "BOM"));
        ddlType.Items.Insert(1, new ListItem("差错单", "CCD"));
        ddlType.Items.Insert(2, new ListItem("进料计划", "JLJH"));
    }
    #endregion

    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        ddlFamily.SelectedValue = string.Empty;
        ddlFactory.SelectedValue = string.Empty;
        ddlTeam.SelectedValue = string.Empty;
        txtQty.Text = string.Empty;
        ddlType.SelectedIndex = 0;
        txtBillID.Value = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtPlanDate.Value = string.Empty;
        ddlStation.SelectedValue = string.Empty;
        txtType.Text = "BOM";
        ItemGrid.Rows.Clear();

        txtProduct.Value = string.Empty;
        txtProductDisp.Value = string.Empty;
        txtStatus.Text = string.Empty;

        txtPlanNoDisp.Value = string.Empty;
        txtPlanNo.Text = string.Empty;
        txtFamilyID.Text = string.Empty;
        txtParentID.Text = string.Empty;
        txtFamilyName.Text = string.Empty;
    }
    #endregion

    #region Excel导出
    protected void btnExport_Click(object sender, EventArgs e)
    {
        if (ItemGrid.Rows.Count == 0)
        {
            Response.Write("<script>alert('未查询，不能导出空数据！')</script>");
            return;
        }

        if (txtBillID.Value == "")
        {
            Response.Write("<script>alert('未保存，不能导出！')</script>");
            return;
        }

        DataTable dtResult = new DataTable();
        dtResult.Columns.Add("FactoryName");
        dtResult.Columns.Add("Sequence");
        dtResult.Columns.Add("WorkStationName");
        dtResult.Columns.Add("ProductName");
        dtResult.Columns.Add("Description");
        dtResult.Columns.Add("QtyRequired");
        dtResult.Columns.Add("Qty");
        dtResult.Columns.Add("WorkflowStr");
        dtResult.Columns.Add("TeamName");

        dtResult.Columns["FactoryName"].Caption = "责任单位";
        dtResult.Columns["Sequence"].Caption = "序号";
        dtResult.Columns["WorkStationName"].Caption = "配送地点";
        dtResult.Columns["ProductName"].Caption = "物料图号";
        dtResult.Columns["Description"].Caption = "名称";
        dtResult.Columns["QtyRequired"].Caption = "需求数量";
        dtResult.Columns["Qty"].Caption = "配送数量";
        dtResult.Columns["WorkflowStr"].Caption = "路线";
        dtResult.Columns["TeamName"].Caption = "班组";

        uMESCommonBusiness rep = new uMESCommonBusiness();
        for (int i = 0; i <= ItemGrid.Rows.Count - 1; i++)
        {
            DataRow dr = dtResult.NewRow();
            if (!string.IsNullOrEmpty(ItemGrid.Rows[i].Cells.FromKey("FactoryName").Text))
            {
                dr["FactoryName"] = ItemGrid.Rows[i].Cells.FromKey("FactoryName").Text.ToString();
            }

            if (!string.IsNullOrEmpty(ItemGrid.Rows[i].Cells.FromKey("Sequence").Text))
            {
                dr["Sequence"] = ItemGrid.Rows[i].Cells.FromKey("Sequence").Text.ToString();
            }

            if (!string.IsNullOrEmpty(ItemGrid.Rows[i].Cells.FromKey("WorkStationName").Text))
            {
                dr["WorkStationName"] = ItemGrid.Rows[i].Cells.FromKey("WorkStationName").Text.ToString();
            }

            if (!string.IsNullOrEmpty(ItemGrid.Rows[i].Cells.FromKey("ProductName").Text))
            {
                dr["ProductName"] = ItemGrid.Rows[i].Cells.FromKey("ProductName").Text.ToString();
            }

            if (!string.IsNullOrEmpty(ItemGrid.Rows[i].Cells.FromKey("Description").Text))
            {
                dr["Description"] = ItemGrid.Rows[i].Cells.FromKey("Description").Text.ToString();
            }

            if (!string.IsNullOrEmpty(ItemGrid.Rows[i].Cells.FromKey("QtyRequired").Text))
            {
                dr["QtyRequired"] = ItemGrid.Rows[i].Cells.FromKey("QtyRequired").Text.ToString();
            }

            if (!string.IsNullOrEmpty(ItemGrid.Rows[i].Cells.FromKey("Qty").Text))
            {
                dr["Qty"] = ItemGrid.Rows[i].Cells.FromKey("Qty").Text.ToString();
            }

            if (!string.IsNullOrEmpty(ItemGrid.Rows[i].Cells.FromKey("WorkflowStr").Text))
            {
                dr["WorkflowStr"] = ItemGrid.Rows[i].Cells.FromKey("WorkflowStr").Text.ToString();
            }

            if (!string.IsNullOrEmpty(ItemGrid.Rows[i].Cells.FromKey("TeamName").Text))
            {
                dr["TeamName"] = ItemGrid.Rows[i].Cells.FromKey("TeamName").Text.ToString();
            }

            dtResult.Rows.Add(dr);
        }

        string strTitle = "进料计划";
        string strType = txtType.Text;
        if (strType == "CCD")
        {
            strTitle = "差错单";
        }
        string content = getExcelContent(dtResult, strTitle);
        ExportToExcel(strTitle + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls", content, "");
    }


    public void ExportToExcel(string filename, string content, string cssText)
    {
        var res = HttpContext.Current.Response;
        content = String.Format("<style type='text/css'>{0}</style>{1}", cssText, content);

        res.Clear();
        res.Buffer = true;
        res.Charset = "UTF-8";
        filename = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(Path.GetFileName(filename)));
        res.AddHeader("Content-Disposition", "attachment; filename=" + filename);
        res.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        res.ContentType = "application/ms-excel;charset=UTF-8";
        // res.ContentType = "application/octet-stream";
        res.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
        res.Write(content);
        res.Flush();
        res.End();
    }
    
    public string getExcelContent(DataTable dt, string strTitle)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("<table borderColor='black' border='1'>");
        sb.AppendFormat("<thead><tr><th colSpan='{0}' bgColor='#ccfefe'>", dt.Columns.Count);
        sb.AppendFormat("{0} {1}", txtFamilyName.Text, strTitle);
        sb.Append("</th></tr><tr>");

        sb.AppendFormat("<th colSpan='{0}' bgColor='#ccfefe' align='left'>", dt.Columns.Count);
        sb.AppendFormat("流水号：{0}", txtPlanNo.Text);
        sb.Append("</th></tr><tr>");

        sb.AppendFormat("<th colSpan='{0}' bgColor='#ccfefe' align='left'>", 4);
        sb.AppendFormat("令号：{0} ", txtProcessNo.Text);
        sb.AppendFormat("<th colSpan='{0}' bgColor='#ccfefe' align='left'>", 5);
        sb.AppendFormat("计划日期：{0} ", txtPlanDate.Value);
        sb.Append("</th></tr><tr>");

        foreach (DataColumn dc in dt.Columns)
        {
            sb.AppendFormat("<th bgColor='#ccfefe'>{0}</th>", dc.Caption);
        }
        sb.Append("</tr></thead>");
        sb.Append("<tbody>");
        foreach (DataRow dr in dt.Rows)
        {
            sb.Append("<tr>");
            foreach (object str in dr.ItemArray)
            {
                if (str.GetType().Name == "String")
                {
                    sb.AppendFormat("<td>{0}</td>", str);
                }
                else if (str.GetType().Name == "Decimal")
                {
                    sb.AppendFormat("<td>{0:D2}</td>", str.ToString());
                }
                else if (str.GetType().Name == "Double")
                {
                    sb.AppendFormat("<td>{0:D2}</td>", str.ToString());
                }
                else if (str.GetType().Name == "Int32")
                {
                    sb.AppendFormat("<td>{0}</td>", str.ToString());
                }
                else if (str.GetType().Name == "DateTime")
                {
                    sb.AppendFormat("<td>{0}</td>", str.ToString());
                }
                else if (str.GetType().Name == "DBNull")
                {
                    sb.AppendFormat("<td></td>");
                }
                else
                {
                    sb.AppendFormat("<td>{0}</td>", str.ToString());
                }
            }
            sb.Append("</tr>");
        }
        sb.Append("</tbody></table>");
        return sb.ToString();
    }
    #endregion

    #region 生成物料计划
    protected void btnRun_Click(object sender, EventArgs e)
    {
        try
        {
            string strType = ddlType.SelectedValue;
            txtType.Text = strType;

            if (strType == "BOM") //BOM
            {
                string strFamilyID = ddlFamily.SelectedValue;

                if (strFamilyID == "")
                {
                    Response.Write("<script>alert('未选择车型或该车型未关联BOM')</script>");
                    return;
                }

                string strQty = txtQty.Text.Trim();
                if (strQty.Trim() == "")
                {
                    Response.Write("<script>alert('请输入台份数')</script>");
                    return;
                }
                if (Regex.IsMatch(strQty, @"^\d*$") == false)
                {
                    Response.Write("<script>alert('台份数应为正整数')</script>");
                    return;
                }
                if (Convert.ToInt32(strQty) <= 0)
                {
                    Response.Write("<script>alert('台份数应大于零')</script>");
                    return;
                }

                //根据BOM获取物料列表
                int intQty = Convert.ToInt32(strQty);
                string strFactoryID = ddlFactory.SelectedValue;
                string strTeamID = ddlTeam.SelectedValue;
                string strStationID = ddlStation.SelectedValue;

                string[] arr = strFamilyID.Split(':');
                string strBOMID = arr[1];
                DataTable dtMaterial = bll.GetMaterial(strBOMID, intQty, strFactoryID, strTeamID, strStationID);
                ItemGrid.DataSource = dtMaterial;
                ItemGrid.DataBind();
            }
            else if (strType == "JLJH" || strType == "CCD") //进料计划/差错单
            {
                string strBillID = txtBillID.Value;
                if (strBillID == "")
                {
                    Response.Write("<script>alert('请选择进料计划')</script>");
                    return;
                }

                //根据进料计划获取物料列表
                string strFactoryID = ddlFactory.SelectedValue;
                string strTeamID = ddlTeam.SelectedValue;
                string strStationID = ddlStation.SelectedValue;
                DataTable dtMaterial = bll.GetMaterial("MaterialPlan", "", strBillID, strFactoryID, strTeamID, strStationID);
                ItemGrid.DataSource = dtMaterial;
                ItemGrid.DataBind();

                try
                {
                    txtProcessNo.Text = dtMaterial.Rows[0]["ProcessNo"].ToString();
                }
                catch
                { }

                try
                {
                    txtPlanDate.Value = Convert.ToDateTime(dtMaterial.Rows[0]["PlanDate"].ToString()).ToString("yyyy-MM-dd");
                }
                catch
                { }

                try
                {
                    txtQty.Text = dtMaterial.Rows[0]["Qty"].ToString();
                }
                catch
                { }

                try
                {
                    txtFamilyID.Text = dtMaterial.Rows[0]["ProductFamilyID"].ToString();
                }
                catch
                { }

                try
                {
                    txtParentID.Text = dtMaterial.Rows[0]["ParentID"].ToString();
                }
                catch
                { }

                try
                {
                    txtPlanNo.Text = dtMaterial.Rows[0]["PlanNo"].ToString();
                }
                catch
                { }

                try
                {
                    txtFamilyName.Text = dtMaterial.Rows[0]["ProductFamilyName"].ToString();
                }
                catch
                { }
            }
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message + "')</script>");
        }
    }
    #endregion

    #region 全选/反选
    //全选
    protected void btnSelectAll_Click(object sender, EventArgs e)
    {
        if (ItemGrid.Rows.Count > 0)
        {
            Boolean boolResult = true;

            if (btnSelectAll.Text == "全选")
            {
                boolResult = true;
                btnSelectAll.Text = "全不选";
            }
            else if (btnSelectAll.Text == "全不选")
            {
                boolResult = false;
                btnSelectAll.Text = "全选";
            }

            foreach (UltraGridRow row in ItemGrid.Rows)
            {
                row.Cells.FromKey("ckSelect").Value = boolResult;
            }
        }
    }

    //反选
    protected void btnReverseSelect_Click(object sender, EventArgs e)
    {
        foreach (UltraGridRow row in ItemGrid.Rows)
        {
            Boolean value = Convert.ToBoolean(row.Cells.FromKey("ckSelect").Value);

            if (value == true)
            {
                row.Cells.FromKey("ckSelect").Value = false;
            }
            else
            {
                row.Cells.FromKey("ckSelect").Value = true;
            }
        }
    }
    #endregion

    #region 删除/添加
    //删除
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        for (int i = ItemGrid.Rows.Count - 1; i >= 0; i--)
        {
            Boolean value = Convert.ToBoolean(ItemGrid.Rows[i].Cells.FromKey("ckSelect").Value);

            if (value == true)
            {
                ItemGrid.Rows.Remove(ItemGrid.Rows[i]);
            }
        }
    }

    //添加
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        string strProductInfo = txtProduct.Value.Trim();
        if (strProductInfo == "")
        {
            Response.Write("<script>alert('请选择物料')</script>");
            return;
        }

        string[] arr = strProductInfo.Split(':');
        string strProductName = arr[0];
        string strProductRev = arr[1];
        string strProductID = arr[2];
        string strProductDesc = arr[3];

        ItemGrid.Rows.Add();
        ItemGrid.Rows[ItemGrid.Rows.Count - 1].Cells.FromKey("ProductName").Value = strProductName;
        ItemGrid.Rows[ItemGrid.Rows.Count - 1].Cells.FromKey("Description").Value = strProductDesc;
        ItemGrid.Rows[ItemGrid.Rows.Count - 1].Cells.FromKey("ProductID").Value = strProductID;

        txtProduct.Value = "";
    }
    #endregion

    #region 保存
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string strType = txtType.Text;

        if (strType != "BOM")
        {
            string strStatus = txtStatus.Text;
            if (strStatus != "0")
            {
                Response.Write("<script>alert('已有配送信息，不允许保存')</script>");
                return;
            }
        }

        #region 检查物料列表是否为空以及计划日期
        if (ItemGrid.Rows.Count <= 0)
        {
            Response.Write("<script>alert('物料列表为空，不允许保存')</script>");
            return;
        }

        string strPlanDate = txtPlanDate.Value.Trim();
        if (strPlanDate == "")
        {
            Response.Write("<script>alert('请输入计划日期')</script>");
            return;
        }
        #endregion

        #region 检查需求数量和序号
        for (int i = 0; i < ItemGrid.Rows.Count; i++)
        {
            string strXQQty = "";
            try
            {
                strXQQty = ItemGrid.Rows[i].Cells.FromKey("QtyRequired").Value.ToString();
            }
            catch
            { }

            if (strXQQty.Trim() == "")
            {
                Response.Write("<script>alert('请输入需求数量')</script>");
                return;
            }
            if (Regex.IsMatch(strXQQty, @"^\d*$") == false)
            {
                Response.Write("<script>alert('需求数量应为正整数')</script>");
                return;
            }
            if (Convert.ToInt32(strXQQty) <= 0)
            {
                Response.Write("<script>alert('需求数量应大于零')</script>");
                return;
            }
        }

        for (int i = 0; i < ItemGrid.Rows.Count; i++)
        {
            string strXH = "";
            try
            {
                strXH = ItemGrid.Rows[i].Cells.FromKey("Sequence").Value.ToString();
            }
            catch
            { }

            if (strXH.Trim() == "")
            {
                Response.Write("<script>alert('请输入序号')</script>");
                return;
            }
            if (Regex.IsMatch(strXH, @"^\d*$") == false)
            {
                Response.Write("<script>alert('序号应为正整数')</script>");
                return;
            }
            if (Convert.ToInt32(strXH) <= 0)
            {
                Response.Write("<script>alert('序号应大于零')</script>");
                return;
            }
        }
        #endregion

        if (strType == "BOM")
        {
            string strJLJHID = Guid.NewGuid().ToString();
            txtFamilyName.Text = ddlFamily.SelectedItem.Text;
            Save(strType, "", strJLJHID);
        }
        else if (strType == "JLJH" || strType == "CCD")
        {
            string strPlanNo = txtPlanNo.Text;
            string strJLJHID = txtBillID.Value.Trim();
            Delete();
            Save(strType, strPlanNo, strJLJHID);
        }

        //btnReSet_Click(null, null);

        Response.Write("<script>alert('保存成功')</script>");
    }

    #region 删除进料计划/差错单
    /// <summary>
    /// 删除进料计划/差错单
    /// </summary>
    protected void Delete()
    {
        string strJLJHID = txtBillID.Value.Trim();

        StringBuilder strSql = new StringBuilder();
        strSql.AppendLine(string.Format("DELETE FROM zzjlplan WHERE ID = '{0}'", strJLJHID));
        OracleHelper.ExecuteSql(strSql.ToString());

        strSql = new StringBuilder();
        strSql.AppendLine(string.Format("DELETE FROM zzjlplandetail WHERE planid = '{0}'", strJLJHID));
        OracleHelper.ExecuteSql(strSql.ToString());
    }
    #endregion

    #region 保存进料计划/差错单
    /// <summary>
    /// 保存进料计划/差错单
    /// </summary>
    protected void Save(string strType, string strPlanNo, string strPlanID)
    {
        //主表
        string strFamilyID = "";

        if (strPlanNo == "")
        {
            strPlanNo = DateTime.Now.ToString("yyyyMMddHHmmss");

            strFamilyID = ddlFamily.SelectedValue;
            string[] arr = strFamilyID.Split(':');
            strFamilyID = arr[0];
        }
        else
        {
            strFamilyID = txtFamilyID.Text;
        }

        string strQty = txtQty.Text.Trim();
        string strProcessNo = txtProcessNo.Text.Trim();
        string strPlanDate = txtPlanDate.Value.Trim();

        string strBillType = "JLJH";
        if (strType == "CCD")
        {
            strBillType = "CCD";
        }

        string strParentID = txtParentID.Text;
        string strCreateID = "";
        string strCreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string strNotes = "";
        string strStatus = "0";

        StringBuilder strSql = new StringBuilder();
        string strJLJHID = Guid.NewGuid().ToString();

        if (strPlanID != "")
        {
            strJLJHID = strPlanID;
        }

        strSql.AppendLine("INSERT INTO zzjlplan(ID,planno,productfamilyid,qty,processno,plandate,billtype,parentid,createid,createdate,notes,status)");
        strSql.AppendLine(string.Format("VALUES('{11}','{0}','{1}',{2},'{3}',to_Date('{4}','yyyy-MM-dd HH24:MI:SS'),'{5}','{6}','{7}',to_date('{8}','yyyy-MM-dd HH24:MI:SS'),'{9}',{10})", strPlanNo, strFamilyID, strQty, strProcessNo, strPlanDate, strBillType, strParentID, strCreateID, strCreateDate, strNotes, strStatus, strJLJHID));
        OracleHelper.ExecuteSql(strSql.ToString());

        //子表
        for (int i = 0; i < ItemGrid.Rows.Count; i++)
        {
            string strSequence = ItemGrid.Rows[i].Cells.FromKey("Sequence").Value.ToString();
            string strFactoryID = "";
            try
            {
                strFactoryID = ItemGrid.Rows[i].Cells.FromKey("FactoryID").Value.ToString();
            }
            catch
            { }

            string strTeamID = "";
            try
            {
                strTeamID = ItemGrid.Rows[i].Cells.FromKey("TeamID").Value.ToString();
            }
            catch
            { }

            string strProductID = ItemGrid.Rows[i].Cells.FromKey("ProductID").Value.ToString();
            string strXQQty = ItemGrid.Rows[i].Cells.FromKey("QtyRequired").Value.ToString();
            string strPSQty = "0";
            if (strType != "BOM")
            {
                try
                {
                    strPSQty = ItemGrid.Rows[i].Cells.FromKey("Qty").Value.ToString();
                }
                catch
                { }
            }

            string strWorkflowStr = "";
            try
            {
                try
                {
                    strWorkflowStr = ItemGrid.Rows[i].Cells.FromKey("WorkflowStr").Value.ToString();
                }
                catch
                { }
            }
            catch
            { }

            string strStationID = "";
            try
            {
                strStationID = ItemGrid.Rows[i].Cells.FromKey("WorkStationID").Value.ToString();
            }
            catch
            { }

            string strDParentID = "";
            try
            {
                strDParentID = ItemGrid.Rows[i].Cells.FromKey("ParentID").Value.ToString();
            }
            catch
            { }

            string strID = "";
            try
            {
                strID = ItemGrid.Rows[i].Cells.FromKey("ID").Value.ToString();
            }
            catch
            { }
            strNotes = "";
            strSql = new StringBuilder();
            string strDetailID = Guid.NewGuid().ToString();

            if (strID != "")
            {
                strDetailID = strID;
            }

            strSql.AppendLine("INSERT INTO zzjlplandetail(Id,planid,Syssequence,sequence,factoryid,teamid,productid,requireqty,qty,workflowstr,workstationid,notes,parentid,status)");
            strSql.AppendLine(string.Format("VALUES('{11}','{0}',{1},{2},'{3}','{4}','{5}',{6},{7},'{8}','{9}','{10}','{12}',0)", strJLJHID, i + 1, strSequence, strFactoryID, strTeamID, strProductID, strXQQty, strPSQty, strWorkflowStr, strStationID, strNotes, strDetailID, strDParentID));
            OracleHelper.ExecuteSql(strSql.ToString());
        }

        if (strType == "BOM")
        {
            ddlType.SelectedValue = "JLJH";
            txtType.Text = "JLJH";
        }

        txtBillID.Value = strJLJHID;
        txtPlanNo.Text = strPlanNo;
        txtFamilyID.Text = strFamilyID;
        txtQty.ReadOnly = true;
        btnRun.Text = "获取物料清单";
    }
    #endregion
    #endregion

    #region 选择类型
    protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
    {
        string strType = ddlType.SelectedValue;
        txtType.Text = strType;
        txtBillID.Value = string.Empty;
        txtPlanNoDisp.Value = string.Empty;
        txtStatus.Text = string.Empty;
        ItemGrid.Rows.Clear();

        txtProcessNo.Text = string.Empty;
        txtPlanDate.Value = string.Empty;

        if (strType == "BOM")
        {
            btnRun.Text = "生成进料计划";
            btnFinish.Visible = false;
            txtQty.ReadOnly = false;
            ddlFamily.Enabled = true;

            txtBillID.Value = string.Empty;
            txtPlanNo.Text = string.Empty;
            txtFamilyID.Text = string.Empty;
            txtParentID.Text = string.Empty;
            txtFamilyName.Text = string.Empty;
        }
        else if (strType == "JLJH")
        {
            btnRun.Text = "获取物料清单";
            btnFinish.Visible = true;
            txtQty.ReadOnly = true;
            ddlFamily.Enabled = true;
        }
        else if (strType == "CCD")
        {
            btnRun.Text = "获取物料清单";
            btnFinish.Visible = true;
            txtQty.ReadOnly = true;
            ddlFamily.Enabled = true;
        }
    }
    #endregion

    #region 完结按钮
    protected void btnFinish_Click(object sender, EventArgs e)
    {
        string strJLJHID = txtBillID.Value.Trim();

        if (strJLJHID == "")
        {
            Response.Write("<script>alert('未选择进料计划或差错单')</script>");
            return;
        }

        StringBuilder strSql = new StringBuilder();
        strSql.AppendLine(string.Format("UPDATE zzjlplan SET status = 3 WHERE ID = '{0}'", strJLJHID));
        OracleHelper.ExecuteSql(strSql.ToString());

        btnReSet_Click(null,null);

        Response.Write("<script>alert('保存成功')</script>");
    }
    #endregion
}